//
//  HomePageCollectionViewCell.m
//  JinMaJiaDemo
//
//  Created by GripMeMory on 16/2/15.
//  Copyright © 2016年 GripMeMory. All rights reserved.
//

#import "HomePageCollectionViewCell.h"
#import "StarLabel.h"

#define kImageHeight 170 / 2
#define kTitleLabelHeight 70 / 2
#define kPriceLabelHeight 65 / 4
#define kCountDownLabelHeight 65 / 4
#define kStarringViewHeight 55 / 2
#define kButtonHeight 55 / 2
#define kFontSize 12

@implementation HomePageCollectionViewCell

{
    UIImageView *_titleImageView;
    UILabel *_titleLabel;
    UILabel *_priceLabel;
    UILabel *_countdownLabel;
    StarLabel *_starringView;
    UIButton *_signupButton;
}

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        _titleImageView = [[UIImageView alloc] init];
        _titleLabel = [[UILabel alloc] init];
        _priceLabel = [[UILabel alloc] init];
        _countdownLabel = [[UILabel alloc] init];
        _starringView = [[StarLabel alloc] init];
        _signupButton = [UIButton buttonWithType:UIButtonTypeCustom];
        
        _signupButton.contentMode = UIViewContentModeCenter;
        [_signupButton setBackgroundImage:[UIImage imageNamed:@"立即报名"] forState:UIControlStateNormal];
        [_signupButton setTitle:@"立即报名" forState:UIControlStateNormal];
        _signupButton.titleLabel.font = [UIFont systemFontOfSize:kFontSize];
        
        [self addSubview:_titleImageView];
        [self addSubview:_titleLabel];
        [self addSubview:_priceLabel];
        [self addSubview:_countdownLabel];
        [self addSubview:_starringView];
        [self addSubview:_signupButton];
    }
    return self;
}

- (void)layoutSubviews{
    _titleImageView.frame = CGRectMake(0, 0, self.width, kImageHeight);
    _titleLabel.frame = CGRectMake(0, _titleImageView.bottom, self.width, kTitleLabelHeight);
    _priceLabel.frame = CGRectMake(0, _titleLabel.bottom, self.width, kPriceLabelHeight);
    _countdownLabel.frame = CGRectMake(0, _priceLabel.bottom, self.width, kCountDownLabelHeight);
    _starringView.frame = CGRectMake(0, _countdownLabel.bottom, self.width, kStarringViewHeight);
    _signupButton.frame = CGRectMake(0, _starringView.bottom, self.width, kButtonHeight);
    
    _titleLabel.textAlignment = NSTextAlignmentLeft;
    _titleLabel.numberOfLines = 2;
    _titleLabel.font = [UIFont boldSystemFontOfSize:kFontSize - 0.5];
    
    _priceLabel.textAlignment = NSTextAlignmentCenter;
    
}

- (void)configureCellWithTwoPicsModel:(HomePageModel *)model{
    
    _titleImageView.image = model.itemImage;
    _titleLabel.text = model.title;
    
    [_priceLabel setAttributedText:[self configurePriceContent:model.price]];
    
    _starringView.selected = model.selected;
    [_starringView setAttributedText:[self configurStarLabelWIthStarNumber:model.starring]];
    
//    [_countdownLabel setAttributedText:[self setContentLabelAttributeStringWithDifference:model.boundTime]];
    
    [self getDifferenceWithBoundTime:model.boundTime withLabel:_countdownLabel];
    
}

- (NSAttributedString *)configurePriceContent:(NSString *)price {
    NSString *string = [NSString stringWithFormat:@"起始价：￥ %@", price];
    NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:string];
    UIFont *markFont = [UIFont italicSystemFontOfSize:14];
    UIFont *normalFont = [UIFont systemFontOfSize:11];
    UIColor *markColor = [UIColor redColor];
    NSDictionary *normalAttributeDic = @{NSFontAttributeName:normalFont, NSUnderlineStyleAttributeName:[NSNumber numberWithInteger:NSUnderlineStyleSingle], NSStrikethroughStyleAttributeName:[NSNumber numberWithInteger:NSUnderlineStyleSingle]};
    NSDictionary *markAttributeDic = @{NSFontAttributeName:markFont, NSForegroundColorAttributeName:markColor, NSUnderlineStyleAttributeName:[NSNumber numberWithInteger:NSUnderlineStyleDouble]};
    NSRange range = [string rangeOfString:@"￥"];
    [attributeString addAttributes:normalAttributeDic range:NSMakeRange(0, range.location)];
    [attributeString addAttributes:markAttributeDic range:NSMakeRange(range.location, string.length - range.location)];
    return attributeString;
}

- (NSMutableAttributedString *)setContentLabelAttributeStringWithDifference:(NSString *)difference{
    NSString *foreString = [NSString stringWithFormat:@"限时报价期:"];
    NSMutableString *backString = [NSMutableString stringWithString:difference];
    [backString insertString:@"天" atIndex:2];
    [backString insertString:@"时" atIndex:5];
    [backString insertString:@"分" atIndex:8];
    [backString insertString:@"秒" atIndex:11];
    [backString insertString:foreString atIndex:0];
    NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:backString];
    UIFont *normalFont = [UIFont systemFontOfSize:11];
    NSDictionary *normalAttributeDic = @{NSFontAttributeName:normalFont};
    [attributeString addAttributes:normalAttributeDic range:NSMakeRange(0, backString.length)];
    return attributeString;
}

- (NSMutableAttributedString *)configurStarLabelWIthStarNumber:(NSString *)starNumber{
    NSString *string = [NSString stringWithFormat:@"%@次围观", starNumber];
    NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:string];
    UIFont *normalFont = [UIFont systemFontOfSize:11];
    NSDictionary *normalAttributeDic = @{NSFontAttributeName:normalFont};
    [attributeString addAttributes:normalAttributeDic range:NSMakeRange(0, attributeString.length)];
    return attributeString;
}

#pragma mark - Bound Time

- (void)getDifferenceWithBoundTime:(NSString *)boundtime withLabel:(UILabel *)label{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = timeFormatter;
    
    NSDate *endTime = [formatter dateFromString:boundtime];
    NSDate *nowTime = [NSDate dateWithTimeIntervalSinceNow:0];
    
    NSTimeInterval end = [endTime timeIntervalSince1970];
    NSTimeInterval now = [nowTime timeIntervalSince1970];
    NSTimeInterval diff = end - now;
    
    __block int timeout = (int)diff;
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0);
    dispatch_source_set_event_handler(_timer, ^{
        
        if(timeout<=0)
        {
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //倒计时结束
                //TODO: 修改modal followState 状态，刷新tableview，通知服务器或重新从服务器拉取数据
                label.text = [NSString stringWithFormat:@"%d",timeout];
            });
        }
        else
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //更新界面
                NSString *lastString = [self updateTime:timeout];
                [label setAttributedText:[self setContentLabelAttributeStringWithDifference:lastString]];
                [self needsUpdateConstraints];
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
    
}

- (NSString *)updateTime:(int)difference{
    
    NSString *day = @"";
    day = [NSString stringWithFormat:@"%02d", difference / 86400];
    
    difference = difference % 86400;
    
    NSString *time = [NSString stringWithFormat:@"%02d", difference / 3600];
    time = [NSString stringWithFormat:@"%@%02d", time, difference / 60 % 60];
    time = [NSString stringWithFormat:@"%@%02d",time, difference % 60 % 60];
    
    
    return [NSString stringWithFormat:@"%@%@", day, time];
}


@end
